package com.jqsoft.launcher.activity.gairui;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcB;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.garea.device.plugin.DevicePluginCategory;
import com.garea.device.plugin.DevicePluginManager;
import com.garea.device.plugin.IDevicePlugin;
import com.garea.device.plugin.idcard.IDCardInspector;
import com.garea.device.plugin.idcard.IIDCardDevice;
import com.garea.device.plugin.idcard.IIDCardPersonInfo;
import com.garea.device.plugin.idcard.OnIDCardListener;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.PersonnelInformation;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.activity.setting.SubmitXianDianListActivity;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.tool.AbstractViewHolder;
import com.jqsoft.launcher.util.BytesTransUtil;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.DateTools;
import com.jqsoft.launcher.util.EcgUtil;
import com.jqsoft.launcher.util.FileService;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.Util;
import com.jqsoft.launcher.util.WebServiceUtils;
import com.otg.idcard.OTGReadCardAPI;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class XDpersonActivity extends JQActivity implements
		View.OnClickListener {
	private final String tag = "XDpersonActivity";
	private ListView listview;// 列表
	private ListAdapter adapter;

	private CheckBox xzCheckbox, current_xzCheckbox;
	private Button chaxuan_btn, totalcount_bt, card_chaxuan_btn;
	private EditText name_et, dangan_num_et, shengfenzheng_et;
	private String name_str, dangan_num_str, shengfenzheng_str;
	private String content;
	private List<PersonnelInformation> infoList = new ArrayList<PersonnelInformation>();
	private boolean notfirstTime = false, isThreadrun = false;
	private long allcount = 0;

	private View moreView;
	private LinearLayout progressBar_ll; // 更多等待层
	private Button moreButton;
	private int jiciNum = 0;// 第几次点击加载更多
	private PersonnelInformation xuanzhong_tiao;
	private Button xindian_jiance_btn, weitijiao_xindian_btn;
	private Button see_xindian_wave_btn;
	private String sPersonID, sNo, sPersonName, sCardNo, IsService = "1";
	private TextView Readingtext;

	/* 请求码 */
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;

	private static final int IMAGE_REQUEST_CODE2 = 3;
	private static final int CAMERA_REQUEST_CODE2 = 4;
	private static final int RESULT_REQUEST_CODE2 = 5;

	private static final int IMAGE_REQUEST_CODE3 = 6;
	private static final int CAMERA_REQUEST_CODE3 = 7;
	private static final int RESULT_REQUEST_CODE3 = 8;
	private static String DB_NAME;
	private static final int DB_VERSION = 2;
	private static DatabaseHelper mOpenHelper;
	private static SQLiteDatabase db2;

    private int ECG_CHECK_REQUEST_CODE=10000;

	private static final int SETTING_SERVER_IP = 11;
	private static final int SETTING_BT = 22;
	public static String remoteIPA = "";
	public static String remoteIPB = "";
	public static String remoteIPC = "";
	private int mode = 2;// 1,OTG; 2, NFC; //3, Bluetooth;

	private NfcAdapter mAdapter = null;
	// private ReadCardAPI NFCReadCardAPI;
	private OTGReadCardAPI ReadCardAPI;
	private PendingIntent pi = null;
	// �˵�����޷���Ӧ�ʹ����Intent
	private IntentFilter tagDetected = null;
	private String[][] mTechLists;
	private Intent inintent = null;

	private int readflag = 0;
	private BluetoothAdapter btAdapt;
	private static final int REQUEST_ENABLE_BT = 2;
	public static String EXTRA_DEVICE_ADDRESS = "device_address";
	public static String addressmac = "";

	public static final int MESSAGE_VALID_OTGBUTTON = 15;
	public static final int MESSAGE_VALID_NFCBUTTON = 16;
	public static final int MESSAGE_VALID_BTBUTTON = 17;
	public static final int MESSAGE_VALID_PROCESS = 1001;

	public static String DB_CREATE_TABLE_IPCONFIG = "CREATE TABLE IF NOT EXISTS [setipconfig] "
			+ "([ID] INTEGER PRIMARY KEY,[IP] VARCHAR)";

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db2) {
			Log.e("ERROR", "test here DBOperation this channel onCreate");
			db2.execSQL(DB_CREATE_TABLE_IPCONFIG);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		}
	}
	@Override
	protected int getContentLayout() {

		return R.layout.xdperson_layout;
	}
	private IDCardInspector mInspector;
	private IIDCardDevice mDevice;
	@Override
	protected void initGui() {
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		this.registerReceiver(mUsbReceiver, filter);
		Readingtext = (TextView) findViewById(R.id.Readingtext);
		xindian_jiance_btn = (Button) findViewById(R.id.xindian_jiance_btn);
		xindian_jiance_btn.setOnClickListener(XDpersonActivity.this);
		listview = (ListView) findViewById(R.id.hbp_diagnosis_lv);
		chaxuan_btn = (Button) findViewById(R.id.chaxuan_btn);
		chaxuan_btn.setOnClickListener(XDpersonActivity.this);
//		card_chaxuan_btn = (Button) findViewById(R.id.card_chaxuan_btn);
//		card_chaxuan_btn.setOnClickListener(this);
		totalcount_bt = (Button) findViewById(R.id.totalcount_bt);
		dangan_num_et = (EditText) findViewById(R.id.dangan_num_et);
		name_et = (EditText) findViewById(R.id.name_et);
		shengfenzheng_et = (EditText) findViewById(R.id.shengfenzheng_et);
		weitijiao_xindian_btn = (Button) findViewById(R.id.weitijiao_xindian_btn);
		weitijiao_xindian_btn.setOnClickListener(XDpersonActivity.this);
		see_xindian_wave_btn = (Button) findViewById(R.id.see_xindian_wave_btn);
		see_xindian_wave_btn.setOnClickListener(XDpersonActivity.this);

		mInspector = DevicePluginManager.getDeviceInspector(DevicePluginCategory.DEV_PLUGIN_CATEGORY_IDCARD_2,
				this);

		mInspector.setOnIDCardDevicePluginListener(new IDCardInspector.OnIDCardDevicePluginListener() {

			@Override
			public void onDiscoverDevice(IIDCardDevice dev) {
				Toast.makeText(XDpersonActivity.this,
						"已连接", Toast.LENGTH_SHORT).show();
				mDevice = dev;
				//自动连接
				dev.setOnDevicePluginStateListener(new DevStateListener());
				dev.setOnIDCardListener(mCardListener);
				dev.init();
			}

			@Override
			public void onMonitorDevice(IIDCardDevice dev) {
				//USB不用本函数
			}
			@Override
			public void onRemovedDevice(IIDCardDevice dev) {
				if (mDevice != null) {
					mDevice.close();
					mDevice.uninit();
					mDevice = null;
				}
			}
		});

		mInspector.init();
		mInspector.searchDevice();
	}
	private class DevStateListener implements IDevicePlugin.OnDevicePluginStateListener {


		public DevStateListener() {

		}

		@Override
		public void onDeviceOpened() {

		}

		@Override
		public void onDeviceInited() {
			mDevice.open();
		}

		@Override
		public void onDeviceUninited() {
			//
		}

		@Override
		public void onDeviceClosed() {
			//
		}

		@Override
		public void onStateChanged(int arg0, int arg1) {
			//
		}
	}
	private OnIDCardListener mCardListener = new OnIDCardListener() {

		@Override
		public void onReceived(IIDCardPersonInfo d) {
			shengfenzheng_et.setText(d.getID());
			name_et.setText(d.getName());
		}

		@Override
		public void onReadFailed() {
		Toast.makeText(XDpersonActivity.this,"读卡失败",Toast.LENGTH_SHORT).show();
		}
	};
	@Override
	protected void initAction() {
		setGoBack();
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				PersonnelInformation obj = (PersonnelInformation) listview
						.getItemAtPosition(position);

				xuanzhong_tiao = obj;
				xzCheckbox = (CheckBox) view.findViewById(R.id.xuanzhong_cb);
				for (int i = 0; i < infoList.size(); i++) {
					infoList.get(i).setCheck(false);
				}
				obj.setCheck(true);
				if (current_xzCheckbox != null) {
					current_xzCheckbox.setChecked(false);
				}
				xzCheckbox.setChecked(true);
				current_xzCheckbox = xzCheckbox;
				adapter.notifyDataSetChanged();
			}

		});
	}

	@Override
	protected void initData() {
		setTitle("心电检测人员列表");
//		if (BphsConstants.sAndroidReader) {
//			chaxuan_btn.setText("读身份证查询");
//			dangan_num_et.setEnabled(false);
//			name_et.setEnabled(false);
//			shengfenzheng_et.setEnabled(false);
//			dangan_num_et.setBackgroundDrawable(getResources().getDrawable(
//					drawable.shape_grayall_corner));
//			name_et.setBackgroundDrawable(getResources().getDrawable(
//					drawable.shape_grayall_corner));
//			shengfenzheng_et.setBackgroundDrawable(getResources().getDrawable(
//					drawable.shape_grayall_corner));
//		}
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {

			sPersonID = bundle.getString("sPersonID");
			sNo = bundle.getString("sNo");
			sPersonName = bundle.getString("sPersonName");
			sCardNo = bundle.getString("sCardNo");
			IsService = bundle.getString("IsService");
			try {
				ComponentName componentName = new ComponentName(
						"com.garea.measurer",
						"com.garea.measurer.app.GEcgActivity");
				Intent newintent = new Intent();
				newintent.setComponent(componentName);
				newintent.putExtra("sexName","女");
				this.startActivityForResult(newintent, 0);
			} catch (Exception e) {
				MessageTools.showDialogOk(ctx, "对不起您没有安装心电插件，请安装心电插件！");
				e.printStackTrace();
			}
			return;
		}

		moreView = getLayoutInflater().inflate(
				R.layout.finance_fund_pagination_more, null);
		moreButton = (Button) moreView.findViewById(R.id.loadMore);
		moreButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (notfirstTime && (allcount > infoList.size())
						&& !isThreadrun) {
					moreButton.setVisibility(View.GONE);
					progressBar_ll.setVisibility(View.VISIBLE);
					jiciNum++;
					new Thread(sendable).start();
				}
			}
		});
		progressBar_ll = (LinearLayout) moreView
				.findViewById(R.id.progressBar_ll);
		Readingtext.setVisibility(View.GONE);
		Readingtext.setText("      正在读卡，请稍候...");
		Readingtext.setTextColor(Color.RED);
		DB_NAME = "/sdcard/yishu/usingservice.db";
		mOpenHelper = new DatabaseHelper(this);
		db2 = mOpenHelper.getWritableDatabase();
		String sql = "";
		Cursor cur;
		sql = "select IP from setipconfig where ID=4;";
		cur = db2.rawQuery(sql, null);
		if (cur.moveToFirst() == true) {
			while (!cur.isAfterLast()) {
				addressmac = cur.getString(0).trim();
				break;
			}
		}
		cur.close();
		db2.close();
		mOpenHelper.close();
		btAdapt = BluetoothAdapter.getDefaultAdapter();// ��ʼ��������������

		ReadCardAPI = new OTGReadCardAPI(getApplicationContext());
		// ReadCardAPI.setpathflag(2);
		// ReadCardAPI.setlogflag(1);
		// mAdapter = NfcAdapter.getDefaultAdapter(this);
		mAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
		if (mAdapter == null) {
			// ReadCardAPI.writeFile("pass new test 2.1");
		} else {
			init_NFC();
			// ReadCardAPI.writeFile("pass new test 2.2");
		}

	}

	private Handler myhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MSG_LOAD_OVER:
				adapter = new ListAdapter();
				notfirstTime = true;
				if (!(infoList.size() == allcount || allcount == 0 || infoList
						.size() <= 0)) {
					// listview.removeFooterView(moreView);
					listview.addFooterView(moreView);
				}
				listview.setAdapter(adapter);
				String count;
				if (infoList.size() > allcount) {
					count = "共计" + infoList.size() + "条）";
				} else {
					count = "共计" + allcount + "条）";
				}
				totalcount_bt.setText("（已加载" + infoList.size() + "条/" + count);
				dismissrogressBar();
				break;
			case Constant.SHOW_UPDATE:
				totalcount_bt.setText("（已加载" + infoList.size() + "条/" + "共计"
						+ allcount + "条）");
				if (infoList.size() >= allcount) {
					listview.removeFooterView(moreView);
				} else {
					progressBar_ll.setVisibility(View.GONE);
					moreButton.setVisibility(View.VISIBLE);
				}
				adapter.notifyDataSetChanged();
				// dismissrogressBar();
				break;
			case Constant.MSG_LOAD_ERROR:
				dismissrogressBar();
				MessageTools.showDialogOk(ctx, "请填写至少一项查询条件,建议填写姓名！");
				break;
			case Constant.TIJIAO_OVER:
				dismissrogressBar();
				setSubmittedEcgPersonStatus();
				MessageTools.showDialogOk(act, "上传成功！");
//				MessageTools.showDialogOkBack(act, "上传成功！");
				break;
			case Constant.TIJIAO_ERROR:
				dismissrogressBar();
				MessageTools.showDialogOk(act, "对不起，上传失败。请重新测试！");
//				MessageTools.showDialogOkBack(act, "对不起，上传失败。请重新测试！");
				break;

			case Constant.BAOCUN_OVER:
				dismissrogressBar();
				MessageTools.showDialogOk(act,
						"保存成功！本次心电数据保存在本机，请到“离线设置”-“上传心电信息”中上传数据！");
//				MessageTools.showDialogOkBack(act,
//						"保存成功！本次心电数据保存在本机，请到“离线设置”-“上传心电信息”中上传数据！");
				break;
			case Constant.BAOCUN_ERROR:
				dismissrogressBar();
				MessageTools.showDialogOk(act, "对不起，保存本地失败。请重新测试！");
//				MessageTools.showDialogOkBack(act, "对不起，保存本地失败。请重新测试！");
				break;
            case Constant.MSG_DISMISS_PROGRESSBAR:
                dismissrogressBar();
                break;
            default:
                break;
			}
			isThreadrun = false;
		}
	};

	// 请求服务器
	private Runnable sendable = new Runnable() {
		public void run() {
			isThreadrun = true;
			String methodName = "GetPersonInfoManageData";//BphsURL.getCommonPath("GetPersonInfoByECG_METHOD");
			String requestUrl = BphsURL.getCommonPath("GetPersonInfoManageData_URL");
			// String requestUrl =
			// "http://60.171.146.122:9098/WebService/Andrews/PsychosisPersonWebService.asmx";
			Log.i(tag, "查询:content" + requestUrl);
			// String methodName="GetPsychosisPersonManageData";
			JSONObject data = new JSONObject();
			// {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
			try {
				UserLoginInfo info = UserLoginInfo.getInstances();
				data.put("sAreaCode", info.getsManagementDivisionCode());//
				if (jiciNum != 0) {
					data.put("iCurrentPageIndex", (jiciNum * 10 + 1) + "");
				} else {
					data.put("iCurrentPageIndex", "1");
				}
				data.put("iPageSize", "10"); //
				data.put("sNo", dangan_num_str); //
				data.put("sPersonName", name_str); //
				data.put("sCardNo", shengfenzheng_str); //
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			content = WebServiceUtils.requestByParams(methodName,
					data.toString(), requestUrl);
			if (StringUtils.isNotBlank(content)) {
				try {
					Log.i(tag, "返回的查询结果" + content);
					// String result= content.replaceAll("\\\\", "");
					// Log.i(tag, "返回的查询结果"+result);
					JSONObject json = new JSONObject(content);
					// Log.i(tag, "返回的查询结果"+result);"AllCount":0,
					// allcount= 28;
					allcount = json.getLong("AllCount");
					JSONObject jo = new JSONObject(json.getString("Data"));
					JSONArray jsonArray = (JSONArray) jo.get("Table");
					for (int i = 0; i < jsonArray.length(); ++i) {
						JSONObject o = (JSONObject) jsonArray.get(i);
						PersonnelInformation info = new PersonnelInformation(
								o.getString("sPersonID"), o.getString("sNo"),
								o.getString("sPersonName"),
								o.getString("sSexName"),
								o.getString("dBirthday"),
								o.getString("sCardNo"),
								o.getString("sHouseholdTypeName"),
								o.getString("sInputDeptName"),
								o.getString("sAreaProvinceName")
										+ o.getString("sAreaCityName")
										+ o.getString("sAreaCountryName")
										+ o.getString("sAreaTownName")
										+ o.getString("sAreaVillageName")
										+ o.getString("sAreaGroup"),
								o.getString("sPhone"),
								o.optString("IsECGTB"));
						if (allcount == 1) {
							info.setCheck(true);
							xuanzhong_tiao = info;
						}
						infoList.add(info);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (notfirstTime) {
					myhandler.sendEmptyMessage(Constant.SHOW_UPDATE);
				} else {
					myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				}
			} else {
                myhandler.sendEmptyMessage(Constant.MSG_DISMISS_PROGRESSBAR);
            }
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.xindian_jiance_btn:
//		    testSpecificECG();
			if (current_xzCheckbox == null || infoList.size() <= 0) {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
				return;
			}
//			if (current_xzCheckbox == null && infoList.size() > 1) {
//				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
//				return;
//			}
			try {
//				ComponentName componentName = new ComponentName(
//						"com.garea.measurer",
//						"com.garea.measurer.app.GEcgActivity");
//				ComponentName comc = new ComponentName(
//						"com.example.gareamedicalexaple",
//						"com.example.gareamedicalexaple.EcgExample");
//				intent.setComponent(comc);
//				this.startActivityForResult(intent, 0);
//				Intent intent2 = new Intent();
//				intent2.setClassName("com.example.gareamedicalexaple", "com.example.gareamedicalexample.EcgExample");
//				startActivityForResult(intent2, 2);

				Intent intent2 = new Intent();
				intent2.setClassName("com.jqsoft.launcher", "com.jqsoft.launcher.activity.gairui.EcgExample");
				intent2.putExtra("personInfo", xuanzhong_tiao);
				startActivityForResult(intent2, ECG_CHECK_REQUEST_CODE);


			} catch (Exception e) {
				MessageTools.showDialogOk(ctx, "对不起您没有安装心电插件，请安装心电插件！");
				e.printStackTrace();
			}
			return;
		case R.id.chaxuan_btn:// 查询按钮
			if (!BphsConstants.isNetAvailable) {
				MessageTools.showDialogOk(ctx, "由于人员数据量大，此功能暂不支持离线操作，请连线操作！");
				return;
			}
			// if (!BphsConstants.sAndroidReader) {
			name_str = name_et.getText().toString().trim();
			dangan_num_str = dangan_num_et.getText().toString().trim();
			shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
			if (infoList.size() > 0) {
				listview.removeFooterView(moreView);
			}
			infoList.clear();
			allcount = 0;
			notfirstTime = false;
			loadWaitPanel();
			new Thread(sendable).start();
			// } else {
			// loadWaitPanel();
			// Intent intent = new Intent(this, CardActivity.class);
			// startActivityForResult(intent, 1);
			// }
			return;
//		case R.id.card_chaxuan_btn:
//			loadWaitPanel();
////			Intent intent = new Intent(this, CardActivity.class);
////			startActivityForResult(intent, 1);
//			return;
		case R.id.weitijiao_xindian_btn:
			toNoFinish(SubmitXianDianListActivity.class);
			return;

			case R.id.see_xindian_wave_btn:
				if (current_xzCheckbox == null || infoList.size() <= 0) {
					MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
					return;
				}
				String isEcg = xuanzhong_tiao.getIsECGTB();
				if (!PersonnelInformation.PERSON_INFO_DONE_ECG.equals(isEcg)){
					MessageTools.showDialogOk(ctx, "此人暂无心电检测记录！");
					return;
				}
				Intent waveIntent = new Intent();
				waveIntent.setClass(this, EcgResultViewerActivity.class);
				waveIntent.putExtra("personInfo", xuanzhong_tiao);
				startActivity(waveIntent);

//				toNoFinish(EcgResultViewerActivity.class);
				break;
			default:
				break;
		}
	}

	private void testSpecificECG(){
        WebServiceUtils.requestSpecificECG();
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (resultCode) {

		case RESULT_OK:
			// 测试成功后，提交
			final EcgData ecg = new EcgData(data);
			// Submit(ecg);
			// 对话框的创建器
			Builder builder = new Builder(this);
			builder.setIcon(getResources().getDrawable(R.drawable.logo_bg));
			builder.setTitle("心电测试完成");
			builder.setMessage("请选择对测试完的数据进行以下哪种操作？");
			builder.setPositiveButton("上传服务器", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (!BphsConstants.isNetAvailable) {
						Toast.makeText(getApplicationContext(),
								"由于没有联网不能上传，所以自动保存到本地！", Toast.LENGTH_SHORT).show();
						Submit(ecg, 1);
					} else {
						Submit(ecg, 0);
					}
					// Toast.makeText(getApplicationContext(), "上传服务器被点击了",
					// 0).show();
				}
			});
			builder.setNegativeButton("取消", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// Toast.makeText(getApplicationContext(), "取消被点击了",
					// 0).show();
				}
			});
			builder.setNeutralButton("保存到本地", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Submit(ecg, 1);
				}
			});
			builder.setCancelable(false);
			builder.create().show();

			// short[] data1=ecg.getData();
			// byte[] result=StringTools.shortArray2ByteArray(data1);
			// String str1=Base64.encodeToString(result, Base64.NO_WRAP);

			// String s=Arrays.toString(data1).replace("[", "").replace("]",
			// "");
			// Toast.makeText(this, s, 1).show();
			// .replace(", ", "").replace("[", "").replace("]", "");
			// SharedPreferences loginlist = getSharedPreferences("LOGIN_INFOS",
			// 0);
			// loginlist.edit().putString("UserNos", str1)
			// .commit();
			break;
		case SETTING_BT:
			if (resultCode != Activity.RESULT_OK) {
				return;
			}
			String address = data.getStringExtra(EXTRA_DEVICE_ADDRESS);
			mOpenHelper = new DatabaseHelper(this);
			db2 = mOpenHelper.getWritableDatabase();
			String sql = "select IP from setipconfig where ID=4;";
			int p = 0;
			Cursor cur;
			cur = db2.rawQuery(sql, null);
			if (cur.moveToFirst() == true) {
				while (!cur.isAfterLast()) {
					p++;
					break;
				}
			}
			cur.close();

			if (p == 0) {
				sql = "insert into setipconfig (ID,IP) values(4,'" + address
						+ "');";
				db2.execSQL(sql);
			} else {
				sql = "update setipconfig set IP='" + address + "'"
						+ " where ID=4" + ";";
				db2.execSQL(sql);
			}
			db2.close();
			mOpenHelper.close();
			addressmac = address;
			ReadCardAPI.setmac(address);
			if (data != null) {
				String cardName = data.getStringExtra("cardName");
				String cardNumber = data.getStringExtra("cardNumber");
				if (requestCode == 1) {
					if (StringUtils.isNotBlank(cardName)
							&& StringUtils.isNotBlank(cardNumber)) {
						name_et.setText(cardName);
						shengfenzheng_et.setText(cardNumber);
						name_str = cardName;
						shengfenzheng_str = cardNumber;
						if (infoList.size() > 0) {
							listview.removeFooterView(moreView);
						}
						infoList.clear();
						allcount = 0;
						notfirstTime = false;
						loadWaitPanel();
						new Thread(sendable).start();
					} else {
						Toast.makeText(this, "读身份证信息失败", Toast.LENGTH_SHORT).show();
					}
				}
			} else {
				Toast.makeText(this, "读身份证信息失败", Toast.LENGTH_SHORT).show();
			}
			break;
//		case 1:
//			dismissrogressBar();
//			if (data != null) {
//				String cardName = data.getStringExtra("cardName");
//				String cardNumber = data.getStringExtra("cardNumber");
//
//				if (StringUtils.isNotBlank(cardName)
//						&& StringUtils.isNotBlank(cardNumber)) {
//					name_et.setText(cardName);
//					shengfenzheng_et.setText(cardNumber);
//					name_str = cardName;
//					shengfenzheng_str = cardNumber;
//					if (infoList.size() > 0) {
//						listview.removeFooterView(moreView);
//					}
//					infoList.clear();
//					allcount = 0;
//					notfirstTime = false;
//					loadWaitPanel();
//					new Thread(sendable).start();
//				} else {
//					Toast.makeText(this, "读身份证信息失败", 0).show();
//				}
//
//			} else {
//				Toast.makeText(this, "读身份证信息失败", 0).show();
//			}
//			break;
		default:
			//MessageTools.showDialogOk(ctx, "检测返回数据失败，不能保存！");
			Log.e(XDpersonActivity.class.getName(), "Other: " + resultCode);
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private byte[] getByteArrayFromShortArray(short[] shortArray){
		if (shortArray==null){
			return new byte[0];
		}
		BytesTransUtil bytesTransUtil = BytesTransUtil.getInstance();
		byte[] byteArray = bytesTransUtil.Shorts2BytesEcg(shortArray);
		return byteArray;
	}

	private short[] getShortArrayFromByteArray(byte[] byteArray){
		if (byteArray==null){
			return new short[0];
		}
		BytesTransUtil bytesTransUtil = BytesTransUtil.getInstance();
		short[] shortArray = bytesTransUtil.Bytes2Shorts(byteArray);
		return shortArray;
	}

	private void setSubmittedEcgPersonStatus(){
        if (xuanzhong_tiao != null) {
//            sPersonID = xuanzhong_tiao.getsPersonID();
//            sNo = xuanzhong_tiao.getsNo();
//            sPersonName = xuanzhong_tiao.getsPersonName();
            String cardNo = xuanzhong_tiao.getsCardNo();
            String checkCardNo = Util.checkString(cardNo);
            if (infoList!=null){
                for (int i = 0; i < infoList.size(); ++i){
                    PersonnelInformation pi = infoList.get(i);
                    String someCardNo = pi.getsCardNo();
                    if (checkCardNo.equals(someCardNo)){
                        pi.setIsECGTB(PersonnelInformation.PERSON_INFO_DONE_ECG);
						break;
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }

    }

    private void saveShortArrayToFile(final String fileName, final short[] data){
        new Thread(new Runnable() {
            @Override
            public void run() {
                EcgUtil.writeShortArrayToFileName(XDpersonActivity.this, fileName, data);
            }
        }).start();
    }

    private void saveBytetArrayToFile(final String fileName, final byte[] data){
        new Thread(new Runnable() {
            @Override
            public void run() {
                EcgUtil.writeBytesToFileName(XDpersonActivity.this, fileName, data);
            }
        }).start();
    }

	private void Submit(final EcgData ecg, final int flag) {
		short[] data1 = ecg.getData();

//        //write test file
//        saveShortArrayToFile(Constant.ECG_TEST_FILE_NAME_SHORT_ARRAY, data1);
//        //write test file end

//		byte[] result = StringTools.shortArray2ByteArray(data1);
		byte[] result = getByteArrayFromShortArray(data1);

//        //write test file 2
//        saveBytetArrayToFile(Constant.ECG_TEST_FILE_NAME_BYTE_ARRAY, result);
//        //write test file 2 end

		final String str1 = Base64.encodeToString(result, Base64.NO_WRAP);
		if (xuanzhong_tiao != null) {
			sPersonID = xuanzhong_tiao.getsPersonID();
			sNo = xuanzhong_tiao.getsNo();
			sPersonName = xuanzhong_tiao.getsPersonName();
			sCardNo = xuanzhong_tiao.getsCardNo();
		}
		loadWaitPanel();
		new Thread() {
			public void run() {
				String methodName = BphsURL
						.getCommonPath("XINDIANAddToECGTB_METHOD");
				String requestUrl = BphsURL
						.getCommonPath("XINDIANECGWebService_URL");
				JSONObject data = new JSONObject();
				// {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
				try {
					UserLoginInfo info = UserLoginInfo.getInstances();
					data.put("sNo", sNo);//
					data.put("sPersonName", sPersonName); //
					data.put("sCardNo", sCardNo); //
					data.put("sECGData", str1); //
					data.put("sECGResult", ecg.getResultText()); //
					data.put("hp", ecg.getHp()); //
					data.put("lp", ecg.getLp()); //
					data.put("notch", ecg.getNotch()); //
					data.put("hr", ecg.getHr()); //
					data.put("pAxis", ecg.getPAxis()); //
					data.put("qrsAxis", ecg.getQrsAxis()); //
					data.put("taxis", ecg.getTAxis()); //
					data.put("prInterval", ecg.getPrInterval()); //
					data.put("qrsDuration", ecg.getQrsDuration()); //
					data.put("qtd", ecg.getQtd()); //
					data.put("qtc", ecg.getQtc()); //
					data.put("rv5", ecg.getRv5()); //
					data.put("sv1", ecg.getSv1()); //
					data.put("rv5sv1", ecg.getRv5sv1()); //
					data.put("pWidth", ecg.getPWidth()); //
					data.put("pExist", ecg.getPExist()); //
					data.put(
							"resultCodes",
							Arrays.toString(ecg.getResultCodes())
									.replace("[", "").replace("]", "")); //
					data.put("sAddUser", info.getsLoginName()); //
					data.put("sInputDeptCode", info.getsOrganizationKey()); //
					data.put("sInputDeptName", info.getsOrganizationName()); //
					data.put("sAreaCode", info.getsManagementDivisionCode()); //
					data.put(
							"dAddTime",
							DateTools
									.getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date())); //
					data.put("sDoctorName", ""); //
					data.put("sPersonID", sPersonID); //
					int isService = Util.getIntFromString(IsService);
					data.put("IsService", isService); //


					//新增字段
					data.put("inputer", userLoginInfo.getsLoginName());//用户名
//					data.put("inputCode", ###);//用户编码
					data.put("inputDate", DateTools.getFormatStringByDF_YYYY_MM_DD(new Date()));//录入日期
					data.put("And_xueya", "0");//
					data.put("And_xinlv", "1");
					data.put("And_xuetang", "0");
					data.put("And_xuehongdanbai", "0");
					data.put("And_tiwen", "0");
					data.put("And_mailv", "0");
					data.put("And_huxipinlv", "0");
					data.put("And_xindian", "1");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				if (flag == 0) {
					content = WebServiceUtils.requestByParams(methodName,
							data.toString(), requestUrl);
					if (StringUtils.isNotBlank(content)) {
						try {
							// {"sSuccess":"1","sMessage":"执行功能！","AllCount":0,"Data":"[]"}
							Log.i(tag, "返回的查询结果" + content);
							JSONObject json = new JSONObject(content);
							String sResult = json.getString("sSuccess");
							if (sResult.equals("1")) {
								myhandler
										.sendEmptyMessage(Constant.TIJIAO_OVER);
							} else {
								myhandler
										.sendEmptyMessage(Constant.TIJIAO_ERROR);
							}
						} catch (Exception e) {
							myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
							e.printStackTrace();
						}
					} else {
						myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
					}
				} else if (flag == 1) {
					try {

						boolean issuccess = new FileService(act).saveToRom(
								sPersonID, sNo, sPersonName, sCardNo,
								"1".equals(IsService) ? "医疗服务心电" : "心电数据",
								data.toString(), "xindian_append.txt");

						if (issuccess) {
							myhandler.sendEmptyMessage(Constant.BAOCUN_OVER);
						} else {
							myhandler.sendEmptyMessage(Constant.BAOCUN_ERROR);
						}
					} catch (Exception e) {
						myhandler.sendEmptyMessage(Constant.BAOCUN_ERROR);
						e.printStackTrace();
					}
				}

			};
		}.start();

	}


	private class ListAdapter extends BaseAdapter {

		public int getCount() {
			return infoList.size();
		}

		public Object getItem(int position) {
			return infoList.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(act);

//			convertView = inflater.inflate(R.layout.xindian_person_item, null);
//			TextView dangan_num_tv = (TextView) convertView
//					.findViewById(R.id.dangan_num_tv);
//			TextView name_tv = (TextView) convertView
//					.findViewById(R.id.name_tv);
//			TextView sex_tv = (TextView) convertView.findViewById(R.id.sex_tv);
//			TextView age_tv = (TextView) convertView.findViewById(R.id.age_tv);
//			TextView shengfenzheng_tv = (TextView) convertView
//					.findViewById(R.id.shengfenzheng_tv);
//			TextView xindian_record_tv = (TextView) convertView.findViewById(R.id.have_xindian_record_tv);
//			TextView changzhu_type_tv = (TextView) convertView
//					.findViewById(R.id.changzhu_type_tv);
//			TextView jiating_address_tv = (TextView) convertView
//					.findViewById(R.id.jiating_address_tv);
//
//			CheckBox cb = (CheckBox) convertView
//					.findViewById(R.id.xuanzhong_cb);

			if (convertView==null) {
				convertView = inflater.inflate(R.layout.xindian_person_item, null);
			}
			TextView dangan_num_tv = (TextView) AbstractViewHolder.get(convertView, R.id.dangan_num_tv);
			TextView name_tv = (TextView) AbstractViewHolder.get(convertView,R.id.name_tv);
			TextView sex_tv = (TextView) AbstractViewHolder.get(convertView,R.id.sex_tv);
			TextView age_tv = (TextView) AbstractViewHolder.get(convertView,R.id.age_tv);
			TextView shengfenzheng_tv = (TextView) AbstractViewHolder.get(convertView, R.id.shengfenzheng_tv);
			TextView xindian_record_tv = (TextView) AbstractViewHolder.get(convertView,R.id.have_xindian_record_tv);
			TextView changzhu_type_tv = (TextView) AbstractViewHolder.get(convertView,R.id.changzhu_type_tv);
			TextView jiating_address_tv = (TextView) AbstractViewHolder.get(convertView,R.id.jiating_address_tv);

			CheckBox cb = (CheckBox) AbstractViewHolder.get(convertView,R.id.xuanzhong_cb);

			dangan_num_tv.setText(infoList.get(position).getsNo());
			name_tv.setText(infoList.get(position).getsPersonName());
			sex_tv.setText(infoList.get(position).getsSexName());

			age_tv.setText(CommonUtil.calcAge2(infoList.get(position)
					.getdBirthday()) + "");
			shengfenzheng_tv.setText(infoList.get(position).getsCardNo());
			String xindianRecordRepresentation = getXindianRecordStringFromFlag(infoList.get(position).getIsECGTB());
			xindian_record_tv.setText(xindianRecordRepresentation);

			changzhu_type_tv.setText(infoList.get(position)
					.getsHouseholdTypeName());

			jiating_address_tv.setText(infoList.get(position)
					.getJiating_address());

			cb.setChecked(infoList.get(position).isCheck());
			if (cb.isChecked()) {
				convertView.setBackgroundColor(Color.parseColor("#ff00CED1"));
			}
			else {
				convertView.setBackgroundColor(Color.WHITE);
			}
			return convertView;
		}

		private String getXindianRecordStringFromFlag(String isEcg){
			if (PersonnelInformation.PERSON_INFO_DONE_ECG.equals(isEcg)){
				return "有";
			} else {
				return "无";
			}
		}
	}
	@Override
	public void onDestroy() {

		// dismissPopupWindow();
		if (mUsbReceiver != null) {
			try {
				this.unregisterReceiver(mUsbReceiver);
			} catch (Exception e) {
				e.printStackTrace();

			}
		}

		super.onDestroy();
        if (mDevice != null) {
            mDevice.close();
            mDevice.uninit();
        }

        if (mInspector != null) {
            mInspector.uninit();
        }
	}
	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (mode == 1) {
			new Builder(XDpersonActivity.this).setTitle("提示")
					.setMessage("目前处于OTG模式！").setPositiveButton("确定", null)
					.show();
			return;
		}
		if (mode == 3) {
			new Builder(XDpersonActivity.this).setTitle("提示")
					.setMessage("目前处于蓝牙模式！").setPositiveButton("确定", null)
					.show();
			return;
		}
		// mHandler.sendEmptyMessageDelayed(MESSAGE_CLEAR_ITEMS, 0);
		if (readflag == 1) {
			return;
		}
		inintent = intent;
		readflag = 1;
		shengfenzheng_et.setText("");
		ReadCardAPI.writeFile("come into onNewIntent 2");
		Readingtext.setVisibility(View.VISIBLE);
		mHandler.sendEmptyMessageDelayed(MESSAGE_VALID_NFCBUTTON, 0);

	}

	@Override
	public void onPause() {
		super.onPause();
		// mAdapter.disableForegroundDispatch(this);
		if (mode == 1)
			return;
		if (mode == 3)
			return;
		if (mAdapter != null)
			stopNFC_Listener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mode == 1)
			return;
		if (mode == 3)
			return;
	//	ReadCardAPI.writeFile("come into onResume 1");
		if (mAdapter != null)
			startNFC_Listener();
//		ReadCardAPI.writeFile("come into onResume 2");
//		ReadCardAPI.writeFile("pass onNewIntent 1.111111 action="
//				+ getIntent().getAction());
	}

	private void startNFC_Listener() {
		mAdapter.enableForegroundDispatch(this, pi,
				new IntentFilter[] { tagDetected }, mTechLists);
		// mAdapter.enableForegroundDispatch(this, pi,
		// new IntentFilter[] { tagDetected }, null);
	}

	private void stopNFC_Listener() {
		mAdapter.disableForegroundDispatch(this);
	}

	private void init_NFC() {
		// nfcIntent = new Intent(getApplicationContext(),
		// interfaceActivity.class)
		// .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
				.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		// tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
		tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);// .ACTION_TAG_DISCOVERED);
		tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
		mTechLists = new String[][] { new String[] { NfcB.class.getName() } };
	}

	private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					UsbDevice device = (UsbDevice) intent
							.getParcelableExtra(UsbManager.EXTRA_DEVICE);

					if (intent.getBooleanExtra(
							UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						if (device != null) {
							mHandler.sendEmptyMessageDelayed(
									MESSAGE_VALID_OTGBUTTON, 0);
						}
					} else {
					}
				}
			}
		}
	};
	private final Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			int tt;
			switch (msg.what) {
			case MESSAGE_VALID_BTBUTTON:
				ReadCardAPI.setmac(addressmac);
				tt = ReadCardAPI.BtReadCard(btAdapt);
				Log.e("For Test", " ReadCard TT=" + tt);
				if (tt == 2) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("接收数据超时！")
							.setPositiveButton("确定", null).show();
				}

				if (tt == 41) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("读卡失败！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 42) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("没有找到服务器！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 43) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("服务器忙！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 90) {
					shengfenzheng_et.setText(ReadCardAPI.CardNo());
					ReadCardAPI.release();
				}

				readflag = 0;
				Readingtext.setVisibility(View.GONE);
				break;
			case MESSAGE_VALID_NFCBUTTON:
				ReadCardAPI.writeFile("come into MESSAGE_CLEAR_ITEMS 1");
				tt = ReadCardAPI.NfcReadCard(inintent);
				// tt=testReadCardAPI.ReadCard();
				ReadCardAPI.writeFile("come into MESSAGE_CLEAR_ITEMS 2");
				Log.e("For Test", " ReadCard TT=" + tt);
				if (tt == 2) {
					 new Builder(XDpersonActivity.this)
					 .setTitle("提示").setMessage("接收数据超时！")
					 .setPositiveButton("确定", null).show();
//					shengfenzheng_et.setText("342401198711176710");
//					getIDCARDINFO();
				}

				if (tt == 41) {
					 new Builder(XDpersonActivity.this)
					 .setTitle("提示").setMessage("读卡失败！")
					 .setPositiveButton("确定", null).show();
//					shengfenzheng_et.setText("342401198711176710");
//					getIDCARDINFO();
				}
				if (tt == 42) {
					 new Builder(XDpersonActivity.this)
					 .setTitle("提示").setMessage("没有找到服务器！")
					 .setPositiveButton("确定", null).show();
//					shengfenzheng_et.setText("342401198711176710");
//					getIDCARDINFO();
				}
				if (tt == 43) {
					 new Builder(XDpersonActivity.this)
					 .setTitle("提示").setMessage("服务器忙！")
					 .setPositiveButton("确定", null).show();
//					shengfenzheng_et.setText("342401198711176710");
//					getIDCARDINFO();
				}
				if (tt == 90) {
					shengfenzheng_et.setText(ReadCardAPI.CardNo());
					ReadCardAPI.release();
					getIDCARDINFO();
				}
				readflag = 0;
				Readingtext.setVisibility(View.GONE);
				break;
			case MESSAGE_VALID_OTGBUTTON:
				tt = ReadCardAPI.ConnectStatus();
				Log.e("For Test", " ConnectStatus TT=" + tt);
				if (tt == 0) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("设备未连接！")
							.setPositiveButton("确定", null).show();

					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 2) {

					Readingtext.setVisibility(View.GONE);
					break;
				}
				tt = ReadCardAPI.OTGReadCard();
				// Log.e("For Test"," ReadCard TT="+tt);
				if (tt == 2) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("接收数据超时！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 41) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("读卡失败！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 42) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("没有找到服务器！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 43) {
					new Builder(XDpersonActivity.this)
							.setTitle("提示").setMessage("服务器忙！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 90) {
					shengfenzheng_et.setText(ReadCardAPI.CardNo());

					String s = ReadCardAPI.CardNo().substring(6, 14);

					ReadCardAPI.release();
					Readingtext.setVisibility(View.GONE);
					break;
				}
				break;
			}
		}
	};
	public void getIDCARDINFO() {
		jiciNum = 1;
		moreButton.setVisibility(View.VISIBLE);
		name_str = name_et.getText().toString().trim();
		dangan_num_str = dangan_num_et.getText().toString().trim();
		shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
		if (infoList.size() > 0) {
			listview.removeFooterView(moreView);
		}
		infoList.clear();
		allcount = 0;
		notfirstTime = false;
		loadWaitPanel();
		new Thread(sendable).start();
	};
}